//
//  segmentedControlView.m
//  ChinaA
//
//  Created by Mxionlly on 2018/11/2.
//  Copyright © 2018 Evan. All rights reserved.
//

#import "segmentedControlView.h"
#import "CommonData.h"
#import <Masonry.h>

@implementation segmentedControlView{
    CGFloat tab1xx;
    CGFloat tabW;
}

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {

    }
    return self;
}

- (void)setItems:(NSArray *)items
{
    _items = items;
    tabW = (KScreenWidth-30)/self.items.count;
    [self segmCheck];
    [self segmCheckIMG];
}


-(UIImageView*)segmCheckIMG{
    if (!_segmCheckIMG) {
        _segmCheckIMG = [[UIImageView alloc]init];
        [self addSubview:_segmCheckIMG];
        tab1xx = (tabW - 60)/2;
        _segmCheckIMG.frame = CGRectMake(tab1xx+15, 45, 60, 2);
        _segmCheckIMG.backgroundColor = COLOR_main;
    }
    return _segmCheckIMG;
}

-(UISegmentedControl*)segmCheck{
    if (!_segmCheck) {
        _segmCheck = [[UISegmentedControl alloc]initWithItems:self.items];
        [self addSubview:_segmCheck];
        [_segmCheck mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerX.mas_equalTo(self);
            make.top.mas_equalTo(self).offset(10);
            make.height.offset(30);
            make.width.mas_equalTo(self).offset(-30);
        }];
        _segmCheck.tintColor = [UIColor clearColor];
        NSDictionary *selected = @{NSFontAttributeName:[UIFont systemFontOfSize:14],NSForegroundColorAttributeName:[UIColor blackColor]};
        NSDictionary *normal = @{NSFontAttributeName:[UIFont systemFontOfSize:14],NSForegroundColorAttributeName:[UIColor blackColor]};
        [_segmCheck setTitleTextAttributes:normal forState:UIControlStateNormal];
        [_segmCheck setTitleTextAttributes:selected forState:UIControlStateSelected];
        
        _segmCheck.selectedSegmentIndex = 0;
        [_segmCheck addTarget:self action:@selector(segmentValueChanged:)forControlEvents:UIControlEventValueChanged];
    }
    return _segmCheck;
}

-(void)segmentValueChanged:(UISegmentedControl*)sender{
    [UIView animateWithDuration:0.3 animations:^{
        self.segmCheckIMG.frame = CGRectMake(self->tabW*sender.selectedSegmentIndex + self->tab1xx+15, 45, 60, 2);
    }];
    if ([self.delegate respondsToSelector:@selector(changesegmentedIndex:)]) {
        [self.delegate changesegmentedIndex:sender.selectedSegmentIndex];
    }
}

@end
